import {isEmpty} from "@/utils";

export default {
  storage: window.localStorage,
  timeout: 7 * 24 * 60 * 60 * 1000,
  setToken(token: string) {
    this.setKey('token', token)
  },
  setUserInfo(userInfo: any) {
    this.setKey('userInfo', userInfo)
  },
  setAppData(appData: any) {
    this.setKey('appData', appData)
  },
  getAppData(): string | null | undefined {
    return this.getValue('appData')
  },
  getUserInfo(): string | null | undefined {
    return this.getValue('userInfo')
  },
  getToken(): string | null | undefined {
    return this.getValue('token')
  },
  setKey(key: string, value: string) {
    let storageValue = StorageValue.createValue(value, this.timeout);
    this.storage.setItem(key, JSON.stringify(storageValue));
  },
  getValue(key: string): string | null | undefined {
    let valueString = this.storage.getItem(key);
    if (isEmpty(valueString)) return null;

    let storageValue: StorageValue = JSON.parse(valueString + '');
    if (this.isExpired(storageValue)) {
      this.remove(key)
      return null;
    } else {
      return storageValue.value;
    }
  },
  logout() {
    this.storage.removeItem('token')
    this.storage.removeItem('userInfo')
  },
  remove(key: string) {
    this.storage.removeItem(key);
  },
  isExpired(storageValue: StorageValue) {
    return new Date().getTime() > storageValue.expiration;
  }
}

class StorageValue {
  value: string | undefined;
  expiration: number = 0;

  static createValue(value: string, timeout: number): StorageValue {
    let res = new StorageValue();
    res.value = value
    res.expiration = new Date().getTime() + timeout;
    return res;
  }
}